using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Markup;

namespace GrpcClient.Models
{
    public class LastItemConverter : MarkupExtension, IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DependencyObject item = (DependencyObject)value;
            ItemsControl ic = ItemsControl.ItemsControlFromItemContainer(item);

            //仅有一项
            if (ic.Items.Count == 1)
            {
                return 0;
            }

            // 第一
            if (ic.ItemContainerGenerator.IndexFromContainer(item) == 0)
            {
                return 1;
            }

            // 最后
            if (ic.ItemContainerGenerator.IndexFromContainer(item) == ic.Items.Count - 1)
            {
                return 3;
            }

            // 其他
            return 2;
        }

        public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
    }
}
